const http = require('http')
const fs = require('fs')

function getData(str){
    var arr = str.split('&')
    var obj = {}
    for(var i = 0;i<arr.length;i++){
        var childArr = arr.split('=')
        obj[childArr[0]]=childArr[1]
    }
    return obj
}

http.createServer((req,res)=>{
    var userList = []
    var urlObj = new URL(req.url,"http://localhost:8080/getdata")
    var pathName = urlObj.pathname
    if(req.url=="/"){
        var fileContent = fs.readFileSync('./post.html')
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.write(fileContent)
        res.end()
    }else if(pathName=='/save'){
        var str = ''
        req.on('data',(chunk)=>{
            str += chunk
        })
        req.on('end',()=>{
            var postObj = getData(str)
            userList.push(postObj)
            res.end('submit success')
        })
    }else if(pathName=='/getlist'){
        var userStr = JSON.stringify(userList)
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.end(userList)
    }
    //删除数据古城，接收请求
    //将userName从userList里删掉

}).listen(8080)